//
//  MyTourWebViewController.m
//  panovtour
//
//  Created by mac on 2022/3/24.
//  Copyright © 2022 refuse. All rights reserved.
//

#import "MyTourWebViewController.h"
#import <WebKit/WebKit.h>
#import <Photos/Photos.h>
#import "FinshUtil.h"


//屏幕宽度
#define SCREEN_WIDTH    (MIN([UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height))
//屏幕高度
#define SCREEN_HEIGHT   (MAX([UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height))

// 颜色
#define colorRGB(r,g,b)             ( [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:(1.0)])
#define colorPure(color)            colorRGB(color,color,color)


@interface MyTourWebViewController ()
@property (nonatomic, strong)WKWebView *webView;
@property (nonatomic, strong)NSString *webViewRequestPath;
@property (nonatomic, assign)CGRect buttonSize;
@property (nonatomic, assign)CGRect imageSize;
@property (nonatomic, assign)CGRect messageSize;
@property (nonatomic, assign)BOOL isHeaderButton;

@property (nonatomic, strong)UIView *pointView;
@property (nonatomic, strong)UIBarButtonItem *rightBarButtonItem;
@property (nonatomic, strong)UILabel *centerLable1;
@property (nonatomic, strong)UIButton *leftButton;
@property (nonatomic, strong)UIButton *rightButton;
@property (nonatomic, strong)UIBarButtonItem *leftBarButtonItem;


@property (nonatomic, assign)CGFloat topSpace;
@property (nonatomic, assign)BOOL isInCurrentView;
@property (nonatomic, assign)BOOL isLoading;

@end

@implementation MyTourWebViewController

- (WKWebView *)webView {
    if(_webView) return _webView;
    //创建配置对象
     WKWebViewConfiguration *conf = [[WKWebViewConfiguration alloc]init];
    //关键代码
     [conf.preferences setValue:@YES forKey:@"allowFileAccessFromFileURLs"];
    //初始化
    CGRect frame =  [UIScreen mainScreen].bounds;
    if(self.isPresent){
        frame.origin.y = self.topSpace;
        frame.size.height = frame.size.height - self.topSpace;
    }
    
    WKWebView *webView = [[WKWebView alloc]initWithFrame:frame configuration:conf];
    _webView = webView;
    return _webView;
}

- (void)initUI {
    [self.view addSubview:self.webView];
    [self addBackTabbarButton];
    NSLog(@"pano : %d", self.isAddBack);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.buttonSize = CGRectMake(0, 0, 44, 44);
    self.messageSize = CGRectMake(SCREEN_WIDTH - 44, 0, 44, 44);
    self.imageSize = CGRectMake(7, 7, 30, 30);
    
    self.view.backgroundColor = [UIColor whiteColor];

    self.webViewRequestPath = [[ NSSearchPathForDirectoriesInDomains ( NSDocumentDirectory , NSUserDomainMask , YES ) lastObject ] stringByAppendingString:@"/web/index.html"];
    
    [self addTopView];
    [self initUI];
    [self initData];
    [[UINavigationBar appearance] setBarTintColor:[UIColor yellowColor]];
}

- (void)initData {
    if(self.imageFile) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            // 耗时的操作
            [FinshUtil cupWithImagePath:self.imageFile];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:self.webViewRequestPath]]];
            });
        });
    } else {
        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:self.webViewRequestPath]]];
    }
}

- (void)addTopView {
    if(self.isShowRight)
        [self addRightTabbarButtonWithTitle:@"保存"];
}

// 顶部安全区高度
- (CGFloat)reSafeDistanceTop {
    if (@available(iOS 13.0, *)) {
        NSSet *set = [UIApplication sharedApplication].connectedScenes;
        UIWindowScene *windowScene = [set anyObject];
        UIWindow *window = windowScene.windows.firstObject;
        return window.safeAreaInsets.top;
    } else if (@available(iOS 11.0, *)) {
        UIWindow *window = [UIApplication sharedApplication].windows.firstObject;
        return window.safeAreaInsets.top;
    }
    return 0;
}

- (void)addRightTabbarButtonWithTitle:(NSString *)title {
    if(self.isPresent){
        CGRect frame = self.buttonSize;
        frame.origin.x = SCREEN_WIDTH - frame.size.width - 20;
        frame.origin.y = [self reSafeDistanceTop];
        UIButton *rightButton = [[UIButton alloc] initWithFrame:frame];
        [rightButton setTitle:title forState:UIControlStateNormal];
        [rightButton setTitleColor:colorPure(51) forState:UIControlStateNormal];
        rightButton.titleLabel.font = [UIFont systemFontOfSize:14];
        
        [rightButton addTarget:self action:@selector(rightButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        self.topSpace = CGRectGetMaxY(frame);
        [self.view addSubview:rightButton];
        
    } else {
        if(self.rightButton){
            [self.rightButton setTitle:title forState:UIControlStateNormal];
        } else {
            UIButton *rightButton = [[UIButton alloc] initWithFrame:self.buttonSize];
            [rightButton setTitle:title forState:UIControlStateNormal];
            [rightButton setTitleColor:colorPure(51) forState:UIControlStateNormal];
            rightButton.titleLabel.font = [UIFont systemFontOfSize:14];
            
            [rightButton addTarget:self action:@selector(rightButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            self.rightButton = rightButton;
            UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
            self.navigationItem.rightBarButtonItem = rightBarButtonItem;
        }
    }
}

- (void)rightButtonClick:(id)sender {
    if(self.isLoading) return;
    self.isLoading = YES;
    PHAuthorizationStatus  author = [PHPhotoLibrary authorizationStatus];
    if (author == PHAuthorizationStatusRestricted || author == PHAuthorizationStatusDenied){
        UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请您先去设置允许APP访问您的相册 设置>隐私>照片" preferredStyle:UIAlertControllerStyleAlert];
        [controller addAction:[UIAlertAction actionWithTitle:@"现在就去" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            if (@available(iOS 10.0, *)) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:^(BOOL success) { }];
            } else {

                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }
        }]];
        [self presentViewController:controller animated:YES completion:nil];
        self.isLoading = NO;

        //无权限 做一个友好的提示
        return ;
    }
    NSString *msg = @"图片下载失败" ;
    if(self.imageFile){
        UIImage *image = [UIImage imageWithContentsOfFile:self.imageFile];
        if(image){
            UIImageWriteToSavedPhotosAlbum(image , self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        } else {
            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.imageFile]];
            if (!data)data =  [NSData dataWithContentsOfFile:self.imageFile];
            if (data) {
                UIImage *image = [UIImage imageWithData:data];
                if(image){
                    UIImageWriteToSavedPhotosAlbum(image , self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
                } else {
                    [self alertMessage:msg];
                }
            } else {
                [self alertMessage:msg];
            }
        }
    } else {
        [self alertMessage:msg];
    }
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    NSString *msg = nil ;
    if(error){
        msg = @"图片下载失败" ;
        [self alertMessage:msg];
    }else{
        msg = @"图片下载成功";
        [self alertMessage:msg];
    }
}

- (void)addBackTabbarButton {
    if (self.isAddBack) {
        if (self.isPresent) {
            [self addLeftBackButton];
        } else {
            [self addLeftTabbarButtonWithImageName:@"back"];
        }
    }
}

- (void)addLeftTabbarButtonWithImageName:(NSString *)name {
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.imageSize];
    if(self.backImage) {
        NSLog(@"this is from out image: %@", self.backImage);
        imageView.image = self.backImage;
    } else {
        NSString *alertImagePath = [self getImagePathWithName:name];
        if(alertImagePath) {
            UIImage *image = [UIImage imageWithContentsOfFile:alertImagePath];
            imageView.image = image;
        }
    }
    [self addLeftTabbarButtonWithView:imageView];
}

- (void)addLeftTabbarButtonWithView:(UIView *)view {
    UIButton *leftButton = [[UIButton alloc] initWithFrame:self.buttonSize];
    [leftButton addSubview:view];
    UIEdgeInsets edge = UIEdgeInsetsMake(3, 0, 3, 0);
    [leftButton setImageEdgeInsets:edge];
    [leftButton addTarget:self action:@selector(leftButtonClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.leftBarButtonItem = leftBarButtonItem;
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
}

- (void)leftButtonClick {
   [self.navigationController popViewControllerAnimated:YES];
}

- (void)addLeftBackButton {
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.imageSize];
    if(self.backImage) {
        imageView.image = self.backImage;
    } else {
//        NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"pano" ofType:@"bundle"]];
//        NSString *alertImagePath = [bundle pathForResource:@"back" ofType:@"png"];
        NSString *alertImagePath = [self getImagePathWithName:@"back" ofType:@"png"];

        UIImage *image = [UIImage imageWithContentsOfFile:alertImagePath];
        imageView.image = image;
    }
    [self addLeftBackButtonWithView:imageView];
}

- (void)addLeftBackButtonWithView:(UIView *)view {
    CGRect frame = self.buttonSize;
    frame.origin.x = 20;
    frame.origin.y = [self reSafeDistanceTop];
    
    UIButton *leftButton = [[UIButton alloc] initWithFrame:frame];
    self.leftButton = leftButton;
    
    [leftButton addSubview:view];
    UIEdgeInsets edge = UIEdgeInsetsMake(3, 0, 3, 0);
    [leftButton setImageEdgeInsets:edge];

    [leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:leftButton];
}

- (void)backAction {
    [self backActionWithAnimated:YES];
}
- (void)backActionWithAnimated:(BOOL)animated {
    if (self.presentingViewController) {
        [self dismissViewControllerAnimated:animated completion:nil];
    } else if (self.navigationController.viewControllers.count > 2 || self.navigationController.topViewController == self) {
        [self.navigationController popViewControllerAnimated:animated];
    }
}
- (void)alertMessage:(NSString *)message {
    self.isLoading = NO;

    UIAlertController *controller = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {}];
    [controller addAction:action];
    [self presentViewController:controller animated:YES completion:nil];
}

- (NSString *)getImagePathWithName:(NSString *)name  {
    return [self getImagePathWithName:name ofType:@"png"];
}

- (NSString *)getImagePathWithName:(NSString *)name ofType:(NSString *)type {
    NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"deviceSdk.framework/pano" ofType:@"bundle"]];
    if(!bundle) {
        NSBundle *bundle1 = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"pano" ofType:@"bundle"]];
        bundle = bundle1;
    }
    if(bundle){
        NSString *alertImagePath = [bundle pathForResource:name ofType:type ? type : @"png"];
        return alertImagePath;
    }
    
    return nil;
}

@end
